<?php

namespace app\model;

use Exception;
use support\Redis;
use think\Model;

class AdminToken extends Model
{
    /**
     * @param SystemAdmin $admin
     * @return array
     * @throws Exception
     */
    public static function adminCreateToken(SystemAdmin $admin): array
    {
        $tokenInfo = $admin->getToken();
        $data      = [
            'uid'          => $admin->id,
            'token'        => $tokenInfo['token'],
            'expires_time' => date('Y-m-d H:i:s', $tokenInfo['params']['exp']),
            'c_time'       => myDate(),
            'date_v'       => date('Y-m-d'),
            'os_type'      => request()->os_type ?? 3,
        ];
        (new self())->replace(true)->save($data);
        return $data;
    }

    /**
     * @param SystemAdmin $admin
     * @return array
     * @throws Exception
     */
    public static function adminLoginToken(SystemAdmin $admin): array
    {
        $_token = AdminToken::adminCreateToken($admin);
        $token  = $_token['token'] ?? '';
        if ($_token) {
            $login_data['uid']               = $admin['id'];
            $login_data['last_login_time']   = myDate();
            $login_data['last_login_date_v'] = date('Y-m-d');
            $login_data['ip']                = request()->getRealIp();
            $login_data['token']             = $token;
            $login_data['os_type']           = request()->os_type ?? 3;
            (new UserLoginLog)->replace(true)->save($login_data);
            $data = [
                [
                    'id'        => $admin['id'],
                    'head_img'  => $admin['head_img'],
                    'username'  => $admin['username'],
                    'phone'     => $admin['phone'],
                    'remark'    => $admin['remark'],
                    'login_num' => $admin['login_num'],
                    'status'    => $admin['status'],
                ],
                $admin['id']
            ];
            Redis::set(ADMIN_TOKEN_LOGIN . $token, json_encode($data), 'EX', 60 * 60 * 24 * 1, 1);
        }
        return $_token;
    }
}